﻿
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using WindowsImageCompressionApp.utils;

namespace SimpleConnection_UDP_WIN.utils.UDP
{
    public class UdpTool
    {
        private UdpClient udpClient;
        private IPEndPoint remoteEndPoint;

        public UdpTool(string remoteIPAddress, int remotePort)
        {
            udpClient = new UdpClient();
            remoteEndPoint = new IPEndPoint(IPAddress.Parse(remoteIPAddress), remotePort);
        }


        /// <summary>
        /// 发送消息不带前缀
        /// </summary>
        /// <param name="message"></param>
        public void SendMessage(string message)
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            udpClient.Send(data, data.Length, remoteEndPoint);
            Console.WriteLine("消息已发送：{0}", message);
            remoteEndPoint = null;
            udpClient.Dispose();
            udpClient = null;
        }

        /// <summary>
        /// 发送消息 带前缀
        /// </summary>
        /// <param name="messageHeader"></param>
        /// <param name="message"></param>
        public void SendMessage(string messageHeader,string message)
        {
            byte[] data = Encoding.UTF8.GetBytes($"{DBUtil.getLocalUserName()} - {messageHeader}:{message}");
            udpClient.Send(data, data.Length, remoteEndPoint);
            Console.WriteLine("消息已发送：{0}", message);
            remoteEndPoint = null;
            udpClient.Dispose();
            udpClient = null;
        }
    }
}